package yancy.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.io.IOException;


/**
 * Created by lwj on 2018/3/27 0027. JSON与POJO互转
 */
@Slf4j
public class JSONUtil {

  /**
   * 将json转化为实体POJO
   */
  public static <T> T JSONToObj(String jsonStr, Class<T> obj) {
    T t = null;
    try {
      ObjectMapper objectMapper = new ObjectMapper();

      t = objectMapper.readValue(jsonStr, obj);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    return t;
  }

  /**
   * 将实体POJO转化为JSON
   */
  public static <T> JSONObject objectToJson(T obj) throws JSONException {
    ObjectMapper mapper = new ObjectMapper();
    String jsonStr = "";
    try {
      jsonStr = mapper.writeValueAsString(obj);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    }
    return new JSONObject(jsonStr);
  }

  /**
   * 将实体POJO转化为字符串
   */
  public static <T> String objectToStr(T obj) {
    ObjectMapper mapper = new ObjectMapper();
    String jsonStr = "";
    try {
      jsonStr = mapper.writeValueAsString(obj);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    }
    return jsonStr;
  }


  public static boolean isValid(String str) {
    ObjectMapper mapper = new ObjectMapper();



    boolean result = true;
    try {
      mapper.readTree(str);
    } catch (IOException e) {
      result = false;
    }
    return result;
  }



//例子


  /**
   * Some readers asked me for an updated version of the one build for three match-ups
   * I posted previously. There is also an increase in demand for beginner builds
   * on /r/allthingsterran recently. This post covers builds for beginners
   * and intermediate players.
   */




//    public static void main(String[] args) throws JSONException, IOException {
//        JSONObject obj = null;
//        obj = new JSONObject();
//        obj.put("name","213");
//        obj.put("age",27);
//        JSONArray array = new JSONArray();
//        array.put(obj);
//        obj = new JSONObject();
//        obj.put("name","214");
//        obj.put("age",28);
//        array.put(obj);
//        Student stu = (Student) JSONToObj(obj.toString(), Student.class);
//        JSONObject objList = newJSONObject();
//        objList.put("student", array);
//        System.out.println("objList:"+objList);
//        StudentList stuList = (StudentList) JSONToObj(objList.toString(), StudentList.class);
//        System.out.println("student:"+stu);
//        System.out.println("stuList:"+stuList);
//        System.out.println("#####################################");
//        JSONObject getObj = objectToJson(stu);
//        System.out.println(getObj);
//    }
}
